//index.js
//获取应用实例
function getAns(num1, op, num2) {
  var ans = 0;
  switch (op) { /* 计算答案 */
    case 1:
      ans = num1 + num2;
      break;
    case 2:
      ans = num1 - num2;
      break;
    case 3:
      ans = num1 * num2;
      break;
    case 4:
      ans = num1 / num2;
      break;
  }
  return ans;
}

function randomRange(myMin, myMax) {
  return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
} //随机数范围


function Formula(num1, num2, num3, op1, op2) {
  this.num1 = num1;
  this.num2 = num2;
  this.num3 = num3;
  this.op1 = op1;
  this.op2 = op2;
  switch (op1) {
    case 1:
      var t = '+';
      break;
    case 2:
      var t = '-';
      break;
    case 3:
      var t = '×';
      break;
    case 4:
      var t = '÷'
  }
  this.op1_str = t;
  switch (op2) {
    case 0:
      var t = null;
      break;
    case 1:
      var t = '+';
      break;
    case 2:
      var t = '-';
      break;
    case 3:
      var t = '×';
      break;
    case 4:
      var t = '÷'
  }
  this.op2_str = t;
  this.ans = this.key = null; //回答和答案
  this.is_true = true; //正误
  this.disabled = false //button是否
  this.calculate = function() { //计算值
    this.key = getAns(this.num1, this.op1, this.num2);
    if (this.op2)
      this.key = getAns(this.key, this.op2, this.num3);
  }
}

function ErrorBook(stem, key) {
  this.stem = stem.toString(); //题干
  this.key = key; //答案
  this.shown = false; //是否显示答案
} //错题本类

var app = getApp();
var ctx = null;

Page({
  data: {
    arr: [],
    clearTime: 1, //1表示计时，0表示不计时
    second: '0' + 0,
    show_second: '0' + 0,
    minute: '0' + 0,
    flex_height: null,
    size: 5.0 + "vw",
    num: 20,
    k: 1,
    grade: 2,
    right: 0,
    problems: [],
    realHeight: null,
    realWidth: null,
    loaded: false, //题目生成完毕？
    head: [
      ["10以内加减法", "20内加减法", "连续100内加减法"],
      ["100以内加减法", "表内乘除法", "100内混合运算"],
      ["四则综合运算", "四则综合运算", "四则混合运算"]
    ],
    draftbook_open: false,
    eraser_open: false,
    canvas_z: -1, //画布的层次
  },
  //初始界面
  onLoad: function(options) {
    this.setInterval();
    this.initCanvas();
    console.log("Value:", options);
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        console.log(res);
        // 屏幕宽度、高度 px
        that.setData({
          realHeight: res.windowHeight,
          realWidth: res.windowWidth,
          num: options.num,
          k: options.k,
          grade: options.grade,
          loaded: false,
          right: 0,
        }) //设置data
      }
    })
    /* 三年级困难字体缩小 */
    if (options.k == 2 && options.grade == 2)
      this.setData({
        size: 4.5 + "vw"
      });
    else
      this.setData({
        size: 5.0 + "vw"
      });

    for (var i = 0; i < this.data.num; i++) {
      if (options.grade == 0) /* 一年级 */ {
        if (options.k == 0) /* 简单：10以内加减法 */ {
          var op1 = randomRange(1, 2);
          var num1 = randomRange(1, 10);
          if (op1 == 2)
            var num2 = randomRange(1, num1);
          else
            var num2 = randomRange(1, 10); //非负
          var formula = new Formula(num1, num2, 0, op1, 0);
        } else if (options.k == 1) /* 中等：20内加减法 */ {
          var op1 = randomRange(1, 2);
          var num1 = randomRange(10, 20);
          if (op1 == 2)
            var num2 = randomRange(5, num1);
          else
            var num2 = randomRange(10, 20); //非负
          var formula = new Formula(num1, num2, 0, op1, 0);
        } else if (options.k == 2) /* 困难：连续10~100加减法 */ {
          var op1 = randomRange(1, 2);
          var op2 = randomRange(1, 2);
          var num1 = randomRange(10, 100);
          var num2 = randomRange(10, 100);
          if (op2 == 2)
            var num3 = randomRange(10, Math.min(getAns(num1, op1, num2), 100));
          else
            var num3 = randomRange(10, 100);
          var formula = new Formula(num1, num2, num3, op1, op2);
        }
      } else if (options.grade == 1) /* 二年级 */ {
        if (options.k == 0) /* 简单：100以内加减法 */ {
          var op1 = randomRange(1, 2);
          var num1 = randomRange(10, 100);
          if (op1 == 2)
            var num2 = randomRange(5, num1);
          else
            var num2 = randomRange(10, 100); //非负
          var formula = new Formula(num1, num2, 0, op1, 0);
        } else if (options.k == 1) /* 中等：表内乘除法 */ {
          var op1 = randomRange(3, 4);
          if (op1 == 3) { //乘法
            var num1 = randomRange(1, 9);
            var num2 = randomRange(1, 9);
          } else { //除法
            var num1 = randomRange(1, 9);
            var num2 = randomRange(1, 9);
            num1 = num1 * num2;
          }
          var formula = new Formula(num1, num2, 0, op1, 0);
        } else if (options.k == 2) { //混合运算
          var op1 = randomRange(3, 4);
          var op2 = randomRange(1, 2);
          if (op1 == 3) { //乘法
            var num1 = randomRange(1, 9);
            var num2 = randomRange(1, 9);
          } else { //除法
            var num1 = randomRange(1, 9);
            var num2 = randomRange(1, 9);
            var product = num1 * num2;
            num1 = product;
          }
          if (op2 == 1)
            var num3 = randomRange(10, 100);
          else
            var num3 = randomRange(10, Math.min(getAns(num1, op1, num2), 100));
          var formula = new Formula(num1, num2, num3, op1, op2);
        }
      } else if (options.grade == 2) /* 三年级 */ {
        if (options.k == 0) /*综合计算*/ {
          var choice = randomRange(1, 3);
          if (choice == 1) { //三位数加减法
            var op1 = randomRange(1, 2);
            var op2 = randomRange(1, 2);
            var num1 = randomRange(100, 1000);
            var num2 = randomRange(100, 1000);
            if (op2 == 2)
              var num3 = randomRange(100, Math.min(getAns(num1, op1, num2), 1000));
            else
              var num3 = randomRange(100, 1000);
            var formula = new Formula(num1, num2, num3, op1, op2);
          } else if (choice == 2) { //三位数x一位数的乘法
            var num1 = randomRange(100, 500);
            var num2 = randomRange(2, 9);
            var formula = new Formula(num1, num2, 0, 3, 0);
          } else { //除法
            var multiplier = randomRange(2, 50); //倍数
            var num2 = randomRange(2, 9);
            var num1 = num2 * multiplier;
            var formula = new Formula(num1, num2, 0, 4, 0);
          }
        } else if (options.k == 1) {
          var choice = randomRange(1, 3);
          if (choice == 1) { //万以下加减法
            var op1 = randomRange(1, 2);
            var num1 = randomRange(100, 5000);
            if (op1 == 2)
              var num2 = randomRange(100, num1);
            else
              var num2 = randomRange(100, 5000);
            var formula = new Formula(num1, num2, 0, op1, 0);
          } else if (choice == 2) { //三位数x一位数的乘法
            var num1 = randomRange(500, 1000);
            var num2 = randomRange(2, 9);
            var formula = new Formula(num1, num2, 0, 3, 0);
          } else { //除法
            var multiplier = randomRange(2, 100); //倍数
            var num2 = randomRange(2, 9);
            var num1 = num2 * multiplier;
            var formula = new Formula(num1, num2, 0, 4, 0);
          }
        } else if (options.k == 2) { //复合运算
          choice = randomRange(1, 2);
          if (choice == 1) { // (1+1)×2类型
            var op2 = randomRange(3, 4);
            if (op2 == 3) {
              var num1 = randomRange(100, 1000);
              var op1 = randomRange(1, 2);
              if (op1 == 2)
                var num2 = randomRange(100, num1);
              else
                var num2 = randomRange(100, 1000);
              var num3 = randomRange(2, 9);
              var formula = new Formula(num1, num2, num3, op1, 3);
            } else {
              var num3 = randomRange(2, 9);
              var multiplier = randomRange(11, 100); //倍数
              var num1 = randomRange(100, 5000);
              var op1 = randomRange(1, 2);
              if (op1 == 1) {
                var num2 = multiplier * num3 - num1;
                if (num2 < 0) {
                  op1 = 2;
                  num2 = -num2;
                }
              } else
                var num2 = num1 - multiplier * num3;
            }
            var formula = new Formula(num1, num2, num3, op1, op2);
          } else { //8×2+2类型
            var op1 = randomRange(3, 4);
            if (op1 == 3) {
              var num1 = randomRange(500, 1000);
              var num2 = randomRange(2, 9);
            } else {
              var multiplier = randomRange(11, 1000);
              var num2 = randomRange(2, 9);
              var num1 = num2 * multiplier;
            }
            var op2 = randomRange(1, 2);
            if (op2 == 2)
              var num3 = randomRange(100, Math.min(getAns(num1, op1, num2), 5000));
            else
              var num3 = randomRange(100, 5000);
          }
          var formula = new Formula(num1, num2, num3, op1, op2);
        }
      }
      formula.calculate();
      if (formula.key < 0) {
        i--;
        continue;
      } //跳过负答案
      this.data.problems.push(formula)
    }
    var query = wx.createSelectorQuery();
    this.setData({
      problems: this.data.problems,
      loaded: true
    })
    /* 根据设备高度动态修改页面 */
    query.select('#rodin').boundingClientRect();
    var _this = this;
    query.exec(function(res) {
      //res就是 该元素的信息 数组
      if (res[0].height <= 0.95 * _this.data.realHeight) {
        _this.setData({
          flex_height: 0.95 * _this.data.realHeight + "px"
        })
      } else {
        _this.setData({
          flex_height: null
        })
      }
    })
  },

  // 计时器
  setInterval: function() {
    const that = this
    var second = that.data.second
    var show_second = '0'
    var minute = '0'

    setInterval(function() { // 设置定时器
      if (that.data.clearTime > 0) {
        second++
        show_second = second % 60
        minute = Math.floor(second / 60)
      }
      if (show_second < 10) {
        // 少于10补零
        that.setData({
          show_second: '0' + show_second
        })
      } else {
        that.setData({
          show_second: show_second
        })
      }
      if (minute < 10) {
        // 少于10补零
        that.setData({
          minute: '0' + minute
        })
      } else {
        that.setData({
          minute: minute
        })
      }
    }, 1000)

  },

  stopMove() {
    return;
  },

  ChangeAns(e) { /* 动态绑定输入内容 */
    var index = e.currentTarget.dataset.index - 1;
    this.setData({
      ["problems[" + index + "].ans"]: e.detail.value
    });
  },
  CheckAns(e) {

    //清除计时器  即清除setInter
    this.data.clearTime = 0;


    for (var index = 0; index < this.data.num; index++) {
      app.globalData.indexAns++;
      if (this.data.problems[index].ans != this.data.problems[index].key) {
        this.data.problems[index].is_true = false;
        //  储存错题
        if (this.data.problems[index].num3==0 || this.data.problems[index].op2 == 0) { //只有两个算式
          var errorbook = new ErrorBook(this.data.problems[index].num1 + this.data.problems[index].op1_str + this.data.problems[index].num2, this.data.problems[index].key);
          app.globalData.wrong.push(errorbook);
        //  console.log(1, errorbook);
        }
         else if (((this.data.problems[index].op1 == 1) || (this.data.problems[index].op1 == 2)) 
         &&((this.data.problems[index].op2 == 3) || (this.data.problems[index].op2 == 4))) {
          var errorbook = new ErrorBook('(' + this.data.problems[index].num1 + this.data.problems[index].op1_str  + this.data.problems[index].num2 + ')' + this.data.problems[index].op2_str + this.data.problems[index].num3, this.data.problems[index].key)
          app.globalData.wrong.push(errorbook);
        //  console.log(2, errorbook);
        } 
        else {
          var errorbook = new ErrorBook(this.data.problems[index].num1  + this.data.problems[index].op1_str  + this.data.problems[index].num2  + this.data.problems[index].op2_str + this.data.problems[index].num3, this.data.problems[index].key);
          app.globalData.wrong.push(errorbook);
          console.log(3,errorbook);
        }
      

      this.data.arr.length = 0;
    } else {
      this.data.problems[index].is_true = 2; //为2则输出tick
      this.data.right += 1;
    }
  }
  this.setData({

    problems: this.data.problems,
    disabled: !this.data.disabled,

  })

  /* 若pages高度不够，则恢复null，弹性高度 */
  var query = wx.createSelectorQuery();
  query.select('#rodin').boundingClientRect();
  var _this = this;
  query.exec(function(res) {
    //res就是 该元素的信息 数组
    if (res[0].height > 0.95 * _this.data.realHeight) {
      _this.setData({
        flex_height: null
      })
    }
  })
  var string = this.data.num + '题你做对了' + this.data.right + '题\n正确率为' + Math.round(100 * this.data.right / this.data.num) + '%\n';
  wx.showToast({
    title: string,
    icon: 'none',
    duration: 5000
  })
},


//画图事件
set_draftbook(e) {
  this.setData({
    draftbook_open: !this.data.draftbook_open,
  })
},
clearAll(e) {
  ctx.draw();
},
pointData: {
  begin_x: 0,
  begin_y: 0,
  end_x: null,
  end_y: null,
},
initCanvas() {
  ctx = wx.createCanvasContext('myCanvas')
  ctx.setLineCap('round')
  ctx.setLineJoin('round')
},
start: function(e) {
  var that = this;
  that.pointData.begin_x = e.touches[0].x;
  that.pointData.begin_y = e.touches[0].y;
  ctx.setStrokeStyle('#000000');
  ctx.setLineWidth('4.5');
  ctx.setLineCap('round'); // 让线条圆润
  ctx.beginPath();
  ctx.moveTo(that.pointData.begin_x, that.pointData.begin_y);
  ctx.lineTo(that.pointData.begin_x, that.pointData.begin_y);
  ctx.stroke();
  ctx.draw(true);
},
move: function(e) {
  var that = this;
  ctx.moveTo(that.pointData.begin_x, that.pointData.begin_y); //把路径移动到画布中的指定点，但不创建线条
  ctx.lineTo(e.touches[0].x, e.touches[0].y); //添加一个新点，然后在画布中创建从该点到最后指定点的线条
  ctx.stroke(); //对当前路径进行描边
  ctx.draw(true);
  that.pointData.begin_x = e.touches[0].x;
  that.pointData.begin_y = e.touches[0].y;
},
end: function(e) {

},


})